package com.medical.config;

import com.medical.service.RedisService;
import com.medical.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * @author TISNIW
 * @version 1.0
 * @desc
 */
@Component
public class JwtAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
//        String token = request.getHeader("Authorization");
//
//        if (token == null || token.isEmpty()) {
//            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "缺少Token");
//            return false;
//        }
//
//        try {
//            Claims claims = JwtUtils.parseToken(token, JwtConstants.SECRET);
//
//            // 可选：验证 Token 是否在 Redis 中存在（防止吊销）
//            Long userId = JwtUtils.getUserIdFromClaims(claims);
//            String redisKey = JwtConstants.TOKEN_REDIS_PREFIX + userId;
//            String cachedToken = redisService.getCacheObject(redisKey, String.class);
//            if (cachedToken == null || !cachedToken.equals(token)) {
//                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token无效或已过期");
//                return false;
//            }
//
//            // 将用户信息放入 request，供 Controller 使用
//            request.setAttribute("userId", userId);
//            request.setAttribute("loginUser", JwtUtils.getLoginUserFromClaims(claims));
//
//            return true;
//
//        } catch (Exception e) {
//            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token解析失败: " + e.getMessage());
//            return false;
//        }
        return true;
    }
}
